package concurrent.cyclicBarrier;

import org.junit.Test;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * 循环栅栏
 *
 * @author LoneRanger
 */
public class CyclicBarrierTest {

	@Test
	public void test() throws InterruptedException {
		CyclicBarrier cyclicBarrier = new CyclicBarrier(7, () -> {
			System.out.println(Thread.currentThread().getName() + "集齐7颗龙珠，召唤神龙");
		});

		for (int i = 1; i <= 7; i++) {
			int finalI = i;
			new Thread(() -> {
				try {
					System.out.println(Thread.currentThread().getName() + "集齐" + finalI + "号龙珠");
					cyclicBarrier.await();
					System.out.println(Thread.currentThread().getName() + "等待" + finalI +
							"号人物，准备许愿啊");
					cyclicBarrier.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				} catch (BrokenBarrierException e) {
					e.printStackTrace();
				}
			}, "thread" + i).start();
		}
		System.out.println(Thread.currentThread().getName() + "许个愿吧");

	}
}
